import intservApi from "@/api/investment/intserv";
import unifiedReportingApi from "@/api/investment/unifiedReporting";

/**
 * 列表序号、列表、搜索、重置、删除、添加/编辑成功、详情、导入、导出、下载模板、是否启用、表格错位问题
 * */
export default {
  data() {
    return {
      MX_list: [],
      MX_total: 0,
      MX_listLoading: false,
      MX_listLength: 0,
      MX_multipleSelection: [],
      MX_headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      MX_pageNav: {
        pageNo: 1,
        pageSize: 10
      },
      // 应用详情
      MX_applicationMsg: {},
      MX_dialogType: '',
      //导入
      MX_fileUploadVisible: false,
      MX_uploadLoading: false
    }
  },
  methods: {
    $_handleSelectionChange(val){
      this.MX_multipleSelection = val;
    },
    // 列表序号
    $_tableIndex(index) {
      return (this.MX_pageNav.pageNo - 1) * this.MX_pageNav.pageSize + index + 1
    },
    $_getRowKey(row) {
      return row.appId
    },
    //获取页面列表
    $_getList(api, params = {}){
      this.MX_listLoading = true
      api(params).then((res) => {
        const data = res.data
        let list = []
        if (data.hasOwnProperty('rows')) {
          list = data.rows
          this.MX_total = Number(data.totalRows)
        }
        if (data.hasOwnProperty('records')) {
          list = data.records
          this.MX_total = Number(data.total)
        }

        this.MX_listLength = list.length
        this.MX_list = list
        this.MX_listLoading = false
      })
    },
    // 搜索
    $_handleFilter() {
      this.MX_pageNav.pageNo = 1
      this.getList()
    },
    // 重置
    $_handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      setTimeout(() => {
        this.$_handleFilter()
      })
    },
    // 删除按钮
    $_handleDelete(api, ids, keyName, tipText = '确定要删除当前数据吗?') {
      this.$dtMessageBox({ title: '提示', message: tipText, type: 'warning' }).then(() => {
        api({[keyName]: ids}).then((res) => {
          this.$dtMessage({
            type: 'success',
            message: '删除成功'
          })
          if (this.MX_listLength == 1) {
            this.MX_pageNav.pageNo--
          }
          this.getList()
        })
      }).catch(() => {
        // 取消不做操作
      })
    },
    // 添加/编辑成功
    $_handleSubmitClose(type, obj) {
      switch (type) {
        case "add":
          this.MX_pageNav.pageNo = 1
          this.getList()
          break;
        case "update":
          this.getList()
          this.MX_applicationMsg = JSON.parse(JSON.stringify(obj))
          break;
        default:
          this.getList()
      }
    },
    //详情按钮
    $_handleDetail(data, api, keyName, callBack, isShowPop){
      if (!!api && !!keyName){
        const loading = this.$loading({
          lock: true,
          text: `查询中...`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        api({[keyName]: data[keyName]}).then((res) => {
          if (!!callBack){
            callBack(res.data)
          }
          if (!!isShowPop){
            this.$refs.dialogForm.open('detail', null, res.data, false)
          }
          loading.close()
        }).catch((r) => {
          loading.close()
        })
      }else{
        this.$refs.dialogForm.open('detail', null, data, false)
      }
    },
    //导入
    async $_handleImport() {
      this.MX_fileUploadVisible = true
      await this.$nextTick()
      this.$refs.dtImportFileRef.fileList = []
    },
    $_importDataSave(api, params = {}, callBack){
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      Object.keys(params).map(v => {
        formData.append(v, params[v])
      })
      this.MX_uploadLoading = true
      api(formData).then((res) => {
        this.MX_fileUploadVisible = false
        if (!!callBack){
          callBack()
        }else{
          this.$message.success('导入成功')
          this.getList()
        }
      }).finally(res => {
        this.MX_uploadLoading = false
      })
    },
    //导出
    $_handleDownload(api, fileName = '', params = {}, tipText = '下载'){
      const downloadLoadingInstance = this.$loading({
        lock: true,
        text: `正在${tipText}...`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      api(params).then((res) => {
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        const objectUrl = URL.createObjectURL(blob)
        const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
        fileName = fileName + '.' + fileType // 指定下载文件名
        this.$_downLoadBlob(objectUrl, fileName)
        downloadLoadingInstance.close()
      }).catch((r) => {
        this.$message.error(`${tipText}文件出现错误，请联系管理员！`)
        downloadLoadingInstance.close()
      })
    },
    $_downLoadBlob(url, fileName){
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = url // 指定下载链接
      a.download = fileName
      a.click()
      URL.revokeObjectURL(a.href) // 释放URL对象
    },
    //是否启用
    $_statusFlagChange(ids = [], sysStatus, keyName, api, isMul = false, tips = ['启用', '禁用']) {
      let msg = sysStatus === 'N' ? tips[1] : tips[0]
      if (!!isMul) {
        if (!this.MX_multipleSelection.length) {
          this.$dtMessageBox({title: '提示', message: `请选择需要进行批量${msg}的数据！`, type: 'warning'})
          return
        }
        ids = this.MX_multipleSelection.map(v => {
          return v[keyName]
        })
      }
      api({[`${keyName}s`]: ids, displayed: sysStatus})
        .then((res) => {
          this.$dtMessage({
            type: 'success',
            message: msg+'成功'
          })
          this.getList()
        }).catch(res => {
        this.$dtMessage({
          type: 'error',
          message: msg+'失败'
        })
        this.getList()
      })
    },
    //修改多个参数
    $_updateFlagChange(ids = [], keyName, api, params = {}, tips = '', isMul = false) {
      if (!!isMul) {
        if (!this.MX_multipleSelection.length) {
          this.$dtMessageBox({title: '提示', message: `请选择需要进行批量${tips}的数据！`, type: 'warning'})
          return
        }
        ids = this.MX_multipleSelection.map(v => {
          return v[keyName]
        })
      }
      api({[!!isMul ? `${keyName}s` : keyName]: ids, ...params})
        .then((res) => {
          this.$dtMessage({
            type: 'success',
            message: tips+'成功'
          })
          this.getList()
        }).catch(res => {
        this.$dtMessage({
          type: 'error',
          message: tips+'失败'
        })
        this.getList()
      })
    },
    //表格错位问题
    $_resetTableLayout() {
      this.$nextTick(() => {
        if (this.$refs.table && this.$refs.table.doLayout) {
          this.$refs.table.doLayout();
        }
      })
    },
  }
}
